package go_framework

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
)

//请求上下文数据结构
type Ctx struct {
	Response    http.ResponseWriter
	Request     *http.Request
	Data        map[string]interface{}
}

//获取请求参数(多个)
func (ctx Ctx) HttpInput(keys []string) (map[string]string, error) {
	r := ctx.Request

	if err := r.ParseForm(); err != nil {
		return nil, err
	}
	m := make(map[string]string)
	for _, key := range keys {
		m[key] = r.FormValue(key)
	}
	return m, nil
}

//获取请求参数(单个)
func (ctx Ctx) HttpInputOne(key string) (string, error) {
	m,err:=ctx.HttpInput([]string{key})

	if err != nil {
		return "", err
	}
	return m[key], nil
}

//从body获取input
func (ctx Ctx) HttpInputFromBody(keys []string) (map[string]string, error) {
	r := ctx.Request

	con, _ := ioutil.ReadAll(r.Body) //获取post的数据

	m := make(map[string]string)
	json.Unmarshal(con,&m);

	return m, nil
}

//跳转
func (ctx *Ctx) Redirect(url string) {
	http.Redirect(ctx.Response, ctx.Request, url, http.StatusFound)
}

//以json响应
func (ctx *Ctx) ResponseJson(out interface{}) {
	b, _ := json.Marshal(out)
	ctx.Response.Write(b)
}